<?php

class Backend_ShoppingController extends RCMS_Core_BaseController {

	protected $_configTableArray;

	protected $_smtpConfigArray;

	protected $_domain;

	protected $_smtpHost;

	protected $_smtpLogin;

	protected $_smtpPassword;

	protected $_adminShoppingEmail;

        protected $_error = array ();

	/**
	 * Init function.
	 * @return <void>
	 */
	public function init()
    {
        parent::init();
        $this->_checkLogin(array('addtocart', 'recount', 'viewsc', 'quoteme', 'handlerpaypalaccount', 'handlerpaypalcreditcard', 'counttax'));
		$this->_model = new Default_Model_ShoppingModel();
		$this->_initSmtp();
	}

	/**
	 * This function loads template where user can add and edit a product.
	 * @return <void>
	 */
	public function productAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
        $this->view->productId = intval($this->getRequest()->getParam('id'));
		$this->view->listFolders = RCMS_Tools_FilesystemTools::scanDir($this->_config->website->website->path . $this->_config->website->website->images);
		$this->view->groups = $this->_model->selectGroups();
		$this->view->products = $this->_model->selectAllProducts();
        $this->view->shoppingConfig = $this->_model->selectShoppingConfig();
        
		//for translator
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
	}

	/**
	 * This function loads template where user can change config for shopping.
	 * @return <void>
	 */
	public function configAction()
    {
	$this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $this->view->update = false;
        
        if ($this->getRequest()->isPost()) {
           /* save settings for shopping config */
            $settingsPayPal = array(
                'email'       =>  trim($this->getRequest()->getParam('paypalemail')),
                'signature'   =>  trim($this->getRequest()->getParam('paypalsignature')),
                'user'        =>  trim($this->getRequest()->getParam('paypaluser')),
                'password'    =>  trim($this->getRequest()->getParam('paypalpassword'))
            );

            $shippingGeneral = $this->getRequest()->getParam('shipping-general');
            $shippingAmount  = $this->getRequest()->getParam('shipping-amount');
            $shippingWeight  = $this->getRequest()->getParam('shipping-weight');
            array_walk_recursive($shippingAmount,array($this,'_validateShippingData'));
            array_walk_recursive($shippingWeight,array($this,'_validateShippingData'));
                        
            $data = array (
                'company'               =>  trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('company'))),
                'phone'                 =>  trim($this->getRequest()->getParam('phone')),
                'email'                 =>  trim($this->getRequest()->getParam('email')),
                'address'               =>  trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('address'))),
                'address2'              =>  trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('address2'))),
                'city'                  =>  trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('city'))),
                'state'                 =>  trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('state'))),
                'zip'                   =>  trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('zip'))),
                'country'               =>  trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('country'))),
                'currency'              =>  trim($this->getRequest()->getParam('currency')),
                'gateway'               =>  trim($this->getRequest()->getParam('gateway')),
                'quote'                 =>  (strtolower($this->getRequest()->getParam('quote')) == 'on' ? '1' : '0'),
                'paypal'                =>  serialize($settingsPayPal),
                'company_logo'          =>  trim($this->getRequest()->getParam('company-logo'))
            );
            if (count($this->_error) == 0){
                foreach ($data as $key => $value) {
                    $this->_model->updateShoppingConfig($key, $value);
                }
                $this->view->error = false;
                $this->view->update = true;
            } else {
                $this->view->error = true;
            }
        }
        /* load settings */
        $this->view->listFolders = RCMS_Tools_FilesystemTools::scanDir($this->_config->website->website->path . $this->_config->website->website->images);
		$this->view->shoppingConfig = $this->_model->selectShoppingConfig();
        $this->view->logoCompany = '';
        if (is_file($this->_config->website->website->path.'public/'.$this->view->shoppingConfig['company_logo'])) {
            $this->view->logoCompany = $this->view->websiteUrl.$this->view->shoppingConfig['company_logo'];
        }
		//for translator
		echo $this->_translator->processScreen($this->view->render($this->getViewScript()));
	}

        /**
         * Load template which let configure products templates and email templates.
         * @return void
         */
        public function templatesAction()
        {
            $this->_helper->getHelper('layout')->disableLayout();
            $this->_helper->viewRenderer->setNoRender(true);
            $this->view->update = false;

            $generator = new RCMS_Object_Generator_Generator();
            
            if ($this->getRequest()->isPost()){
                $quoteResponderBody = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('quote-auto-responder-body')));
                $quoteResponderSubj = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('quote-auto-responder-subject')));
                $quoteEmailSubj     = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('quote-email-subject')));
                $quoteEmailBody     = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('quote-email-body')));

                $data = array (
                    'template_product'      =>  trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('template-product'))),
                    'template_prod_list'    =>  trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('template-prod-list'))),
                    'quote_responder_subj'  =>  (!empty($quoteResponderSubj) ? $quoteResponderSubj : 'A new quote request on '.$this->getWebSiteUrl()),
                    'quote_responder_body'  =>  (!empty($quoteResponderBody) ? $quoteResponderBody : $generator->generateQuoteResponderBody()),
                    'quote_email_subj'      =>  (!empty($quoteEmailSubj) ? $quoteEmailSubj : 'Quote'),
                    'quote_email_body'      =>  (!empty($quoteEmailBody) ? $quoteEmailBody : $generator->generateQuoteMailToUser()),
                    );
                foreach ($data as $key => $value) {
                    $this->_model->updateShoppingConfig($key, $value);
                }
                $this->view->update = true;
            }
            unset($generator);
            //load config
            $this->view->shoppingConfig = $this->_model->selectShoppingConfig();
            //show screen
            echo $this->_translator->processScreen($this->view->render($this->getViewScript()));
        }

	/**
	 * This function loads images for selected folder. (AJAX)
	 * @return <string> (json)
	 */
	public function loadimagesAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if ($this->getRequest()->isPost()) {
			$folder = trim($this->getRequest()->getParam('folder'));
			if ($folder === '') { return; }
			$smallImages = RCMS_Tools_FilesystemTools::scanDir($this->_config->website->website->path . $this->_config->website->website->images . $folder . '/small/');
			$path = $this->_config->website->website->url . 'images/' . $folder . '/';
			$contentSmallImages = '<div style="border-bottom:1px solid #7c7c7c;margin-bottom:3px;height:20px;text-align:right;" onclick="this.parentNode.style.display=\'none\';"><span style="cursor:pointer;color:#7c7c7c;font-weight:bold;"> Close </span></div>';
			if (count($smallImages) > 0) {
				foreach ($smallImages as $image) {
					$contentSmallImages .= '<img title="' . $image . '"  onclick="shop.selectImage(\'' . $path . 'small/' . $image . '\');" style="vertical-align:top; margin: 0px 0px 1px 1px;cursor:pointer;" border="0" width="55" src="' . $path . 'small/' . $image .'">';
				}
				$contentSmallImages .= '<div style="clear:both;height:0px;">&nbsp;</div>';
			}
			echo json_encode(array('small' => $contentSmallImages)); return;
		}
	}

	/**
	 * This function adds new group. (AJAX)
	 * @return <string> (json)
	 */
	public function addgroupAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if ($this->getRequest()->isPost()) {
			$group = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('group', '')));
			if ($group === '') {
				echo json_encode(array('exist' => false, 'save' => false)); return;
			}
			$ifExist = $this->_model->selectGroupByName($group);
			if (!empty($ifExist)) {
				echo json_encode(array('exist' => true, 'save' => false)); return;
			}
			$result = (integer) $this->_model->insertGroup($group);
			if ($result > 0) {
				echo json_encode(array('exist' => false,'save' => true, 'id' => $result)); return;
			}
		}
	}

	/**
	 * This function deletes a group. (AJAX)
	 * @return <string> (json)
	 */
	public function deletegroupAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if ($this->getRequest()->isPost()) {
			$id = (integer) $this->getRequest()->getParam('id', 0);
			if ($id === 0) {
				echo json_encode(array('del' => false)); return;
			}
			$result = $this->_model->deleteGroup($id);
			if ($result > 0) {
				echo json_encode(array('del' => true)); return;
			}
		}
	}

	/**
	 * This function returns data about products for shopping. (AJAX)
	 * @return <string>
	 */
	public function productsforautocompleteAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if ($this->getRequest()->isPost()) {
			$products = $this->_model->selectAllProducts();
			$dataProducts = '';
			if (is_array($products) && count($products) > 0) {
				foreach ($products as $product) {
					$dataProducts .= $product['name'] . ':::' . $product['photo'] . ':::' . $product['id'] . ':::' . $product['item_id'] . '###';
				}
			}
			echo $dataProducts; return;
		}
	}

	/**
	 * This function adds new product. (AJAX)
	 * @return <string> (json)
	 */
	public function addproductAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
        
		if ($this->getRequest()->isPost()) {
            /* got variables */
			$name = trim($this->getRequest()->getParam('name'));
			$itemId = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('item_id')));
			$price = $this->getRequest()->getParam('price');
            $weight = $this->getRequest()->getParam('weight');
            $tax = $this->getRequest()->getParam('tax'); 
			$photo = trim($this->getRequest()->getParam('photo'));
			$brand = strtoupper(trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('brand'))));
			$desc = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('desc')));
			$options = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('options')));
			$related = rtrim($this->getRequest()->getParam('related'), ',');
			$groups = explode(',', rtrim($this->getRequest()->getParam('groups'), ','));
            /* create new product */
			$product = new RCMS_Object_Product_Product();
			$product->setName($name);
			$product->setItemId($itemId);
			$product->setPrice($price);
            $product->setWeight($weight);
			$product->setPhoto($photo);
			$product->setBrand($brand);
			$product->setDescription($desc);
			$product->setOptions($options);
			$product->setRelated($related);
            $product->setTax($tax);
			$idProduct = $product->save();
            
			if ($idProduct > 0) {
				$product->setId($idProduct);
				if(isset($groups[0]) && $groups[0]) {
					$product->setGroups($groups);
				}
                /* generate xml file for products */
                $xmlProducts = new RCMS_Object_Product_ProductFeed();
                $xmlProducts->generateFullProductXML();
                /* save page */
				$ifSave = $this->_savePageForProduct($product);
				$pageUrl = $ifSave === true ? preg_replace('/([@!.:;\'"`$%?&()*|\s\/\\\])/', '-', $product->getName().'-'.$product->getItemId()) : '';
				echo json_encode(array('id' => $idProduct, 'url' => $pageUrl)); return;
			}
			echo json_encode(array('id' => 0)); return;
		}
	}

	/**
	 * This function creates and saves a page for a product.
	 * @param <object> $product
	 * @return <boolean>
	 */
	private function _savePageForProduct(RCMS_Object_Product_Product $product)
    {
        $templateForProduct = $this->_model->selectTemplateByName('product');
        if (!$templateForProduct) {
            $templateForProduct = $this->_model->selectTemplateByName('default');
        }
        $idCategoryProduct = $this->_model->selectCategoryProducts();
        if (!$idCategoryProduct) {
            $idCategoryProduct = $this->_model->insertCategoryProducts(0, RCMS_Object_QuickConfig_QuickConfig::$productsCategoryName);
            $pageCategory = new RCMS_Object_Page_Page();
            $pageCategory->setH1Tag(RCMS_Object_QuickConfig_QuickConfig::$productsCategoryName);
            $pageCategory->setHeaderTitle(RCMS_Object_QuickConfig_QuickConfig::$productsCategoryName);
            $pageCategory->setUrl(RCMS_Object_QuickConfig_QuickConfig::$productsCategoryUrl);
            $pageCategory->setNavName(RCMS_Object_QuickConfig_QuickConfig::$productsCategoryName);
            $pageCategory->setMetaDescription('');
            $pageCategory->setShortDescription('');
            $pageCategory->setCategoryId($idCategoryProduct);
            $pageCategory->setTemplateId($templateForProduct);
            $pageCategory->setFeaturedId(0);
            $pageCategory->setIs404Page(0);
            $pageCategory->setOrder(100);
            $ownerId = unserialize($this->_session->currentUser)->getId() > 0 ? unserialize($this->_session->currentUser)->getId() : 0;
            $pageCategory->setOwner($ownerId);
            $pageCategory->setSeosambaRuleId(0);
            $pageCategory->setShowInMenu(1);
            $pageCategory->setSiloId(0);
            $pageCategory->setStaticOrder(100);
            $pageCategory->setBestPractices(0);
            $pageCategory->setLastUpdate(date("Y-m-d H:i:s"));
            $pageCategory->setWeight(0);
            $pageCategory->setTargetedKeyPhrase(RCMS_Object_QuickConfig_QuickConfig::$productsCategoryName);
            $pageCategory->save();
            unset ($pageCategory);
        }
        $pageUrl = preg_replace('/([@!.:;\'"`$%?&()*|\s\/\\\])/', '-', $product->getName().'-'.$product->getItemId());
        $idCategoryForPage = $this->_model->insertCategoryProducts($idCategoryProduct, $pageUrl);
        $page = new RCMS_Object_Page_Page();
        $page->setH1Tag($pageUrl);
        $page->setHeaderTitle($pageUrl);
        $page->setUrl($pageUrl);
        $page->setNavName($pageUrl);
        $page->setMetaDescription($product->getDescription());
        $page->setShortDescription($product->getDescription());
        $page->setCategoryId($idCategoryForPage);
        $page->setTemplateId($templateForProduct);
        $page->setFeaturedId(0);
        $page->setLastUpdate(date("Y-m-d H:i:s", time()));
        $page->setIs404Page(0);
        $page->setOrder(100);
        $ownerId = unserialize($this->_session->currentUser)->getId() > 0 ? unserialize($this->_session->currentUser)->getId() : 0;
        $page->setOwner($ownerId);
        $page->setSeosambaRuleId(0);
        $page->setShowInMenu(1);
        $page->setSiloId(0);
        $page->setStaticOrder(100);
        $page->setBestPractices(0);
        $page->setWeight(0);
        $page->setTargetedKeyPhrase($pageUrl);
        $save = $page->save();
        if ($save !== false) {
            $product->setPageId($save);
            $product->save();
            $template = new RCMS_Object_Template_Template($templateForProduct);
            preg_match('/content:(.*)}/', $template->getContent(), $matches);
            if (isset($matches[1])) {
                $this->_saveConatainer($matches[1], $save);
            }
            unset ($template);
            unset ($page);
            return true;
        }
        return false;
	}

    /**
     * This function saves a container.
     * @param <string> $name
     * @param <integer> $pageId
     * @return <boolean>
     */
    private function _saveConatainer($name, $pageId)
    {
        $name = trim($name);
        $pageId = (integer)$pageId;
        if ($name == '' || $pageId <= 0) {
            return false;
        }
        $container = new RCMS_Object_Container_Container();
        $container->setType(1);
        $container->setUserId(unserialize($this->_session->currentUser)->getId());
        $container->setPageId($pageId);
        $container->setName($name);
        $container->setPublished(true);
        $container->setIsForSale(true);
        $container->setAllowComments(true);
        $container->setPublishingDate(date('Y-n-d G-i-s'));
        $container->setContent('{$product}');
        $save = $container->save();
        unset ($container);
        if ($save !== false) {
            return true;
        }
        return false;
    }

	/**
	 * This function returns data about a product. (AJAX)
	 * @return <string> (json)
	 */
	public function getdataproductAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if ($this->getRequest()->isPost()) {
			$id = (int) $this->getRequest()->getParam('id');
			$product = new RCMS_Object_Product_Product($id);
			if ($product->getId() > 0) {
				$gr = $product->getGroups();
				$groups = '';
				foreach ($gr as $g) {
					$groups .= $g['id'].',';
				}
                $groups = rtrim($groups, ',');
				$page = new RCMS_Object_Page_Page($product->getPageId());
				$data = array(
					'id'        => $product->getId(),
					'name'      => $product->getName(),
					'item_id'   => $product->getItemId(),
					'brand'     => $product->getBrand(),
					'price'     => $product->getPrice(),
                                        'weight'    => $product->getWeight(),
					'photo'     => $product->getPhoto(),
					'desc'      => $product->getDescription(),
					'options'   => $product->getOptions(),
					'related'   => $product->getRelated(),
					'groups'    => $groups,
					'pageurl'   => $page->getUrl(),
                    'tax'       => $product->getTax()
				);
                unset ($page);
                unset ($product);
				echo json_encode($data); return;
			}
			echo json_encode(array('id' => 0)); return;
		}
	}

	/**
	 * This function deletes a product. (AJAX)
	 * @return <string> (json)
	 */
	public function deleteproductAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
        
		if ($this->getRequest()->isPost()) {
			$id = (int) $this->getRequest()->getParam('id');
			$product = new RCMS_Object_Product_Product($id);
			if ($product->getId() <= 0) {
				echo json_encode(array('del' => false)); return;
			}
			$flagDelete = $product->delete();
			if ($flagDelete) {
                /* generate xml file for products */
                $xmlProducts = new RCMS_Object_Product_ProductFeed();
                $xmlProducts->generateFullProductXML();
				$page = new RCMS_Object_Page_Page($product->getPageId());
				$page->delete();
				echo json_encode(array('del' => true)); return;
			}
			echo json_encode(array('del' => false)); return;
		}
	}

	/**
	 * This function edits a product. (AJAX)
	 * @return <string> (json)
	 */
	public function editproductAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
        
		if ($this->getRequest()->isPost()) {
			$id = (int) $this->getRequest()->getParam('id');
			$name = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('name')));
			$itemId = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('item_id')));
			$price = $this->getRequest()->getParam('price');
            $weight = $this->getRequest()->getParam('weight');
            $tax = $this->getRequest()->getParam('tax'); 
			$photo = trim($this->getRequest()->getParam('photo'));
			$brand = strtoupper(trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('brand'))));
			$desc = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('desc')));
			$options = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('options')));
			$related = rtrim($this->getRequest()->getParam('related'), ',');
			$groups = explode(',', rtrim($this->getRequest()->getParam('groups'), ','));
			$product = new RCMS_Object_Product_Product($id);
			if ($product->getId() <= 0) {
				echo json_encode(array('save' => false)); return;
			}
			$product->setName($name);
			$product->setItemId($itemId);
			$product->setPrice($price);
            $product->setWeight($weight);
			$product->setPhoto($photo);
			$product->setBrand($brand);
			$product->setDescription($desc);
			$product->setOptions($options);
			$product->setRelated($related);
            $product->setTax($tax);
			$save = $product->save();
			if ($save !== false) {
				$product->setGroups($groups);
                                /* generate xml file for products */
                                $xmlProducts = new RCMS_Object_Product_ProductFeed();
                                $xmlProducts->generateFullProductXML();
				echo json_encode(array('save' => true)); return;
			}
			echo json_encode(array('save' => false)); return;
		}
	}

    /**
     * This function returns brands. (AJAX)
     * @return <string>
     */
    public function getbrandsAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
        
		if ($this->getRequest()->isPost()) {
			$brands = $this->_model->selectBrands();
			$out = '';
			if (is_array($brands) && count($brands) > 0) {
				foreach ($brands as $brand) {
					$out .= $brand['brand'].'###';
				}
			}
			echo $out;
		}
	}

    /**
     * This function updates a group.
     * @return <string> (json)
     */
	public function editgroupAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
        
		if ($this->getRequest()->isPost()) {
			$id = (integer) $this->getRequest()->getParam('id');
			$name = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('name')));
			if ($name === '' || $id <= 0) {
				echo json_encode(array('save' => false)); return;
			}
			$save = $this->_model->updateGroup($name, $id);
			if ($save !== false) {
				echo json_encode(array('save' => true)); return;
			}
			echo json_encode(array('save' => false)); return;
		}
	}

	public function addtocartAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		if ($this->getRequest()->isPost()) {
			$id = intval($this->getRequest()->getParam('id'));
			$options = $this->getRequest()->getParam('opts');
			if($options) {
				$itemOptions = array();
				$explodedOpt = explode(',', $options);
				if(sizeof($explodedOpt) > 0) {
					foreach ($explodedOpt as $optionData) {
						$explodedOptData = explode('=', $optionData);
						if(sizeof($explodedOptData) > 0) {
							$itemOptions[$explodedOptData[0]] = $explodedOptData[1];
						}
					}
				}
			}
			$shoppingCart = new RCMS_Object_Shopping_ShoppingCart();
			$shoppingCart->addItem(array(
				'id' => $id,
				'options' => is_array($itemOptions) ? $itemOptions : array()
			));
			echo json_encode(array('itemsCount' => $shoppingCart->getItemsCountForCart(), 'totalPrice' => $shoppingCart->getTotalPrice()));
		}
	}

	public function viewscAction()
    {
        $this->_helper->viewRenderer->setNoRender(true);
		$shoppingConfig = $this->_model->selectShoppingConfig();
		$shoppingCart = new RCMS_Object_Shopping_ShoppingCart();
		$this->view->products = $shoppingCart->getProductsList();
		$this->view->total = $shoppingCart->getTotalPrice();

		$taxableItemsData = $shoppingCart->getTaxableItemsData();
                
        $shippingData = new RCMS_Object_Shipping_Shipping();
        $shipping = ($shoppingConfig['shipping_type'] != 'pickup' ? $shippingData->getShippingCost() : '0');

        if ($shoppingConfig['shipping_type'] == 'pickup'){
            $taxRules = unserialize($shoppingConfig['tax-rules']);
            foreach ($taxRules as $rule) {
                if (in_array('pickup',$rule)){
                    $totalTax = $this->_countTotalTax($taxableItemsData, $rule['tax']);
                }
            }
        } else {
            $totalTax = ($this->_session->totalTax ? $this->_session->totalTax : 0); //$this->_countTotalTax($taxableItemsData, $shoppingConfig['tax']);
        }

        $this->view->currency        = isset($shoppingConfig['currency']) && strlen($shoppingConfig['currency']) == 3 ? $shoppingConfig['currency'] : '';
        $this->view->config          = $shoppingConfig;
        $this->view->settingsPayPal  = unserialize($shoppingConfig['paypal']);
        $this->view->logoPath        = $this->getWebSiteUrl();
        $this->view->companyLogoName = $shoppingConfig['company_logo'];
        $this->view->companyName     = $shoppingConfig['company'];
        $this->view->companyEmail    = $shoppingConfig['email'];
        $this->view->companyPhone    = $shoppingConfig['phone'];
        //$this->view->tax             = 0; //$shoppingConfig['tax'];
        $this->view->totalTax        = number_format($totalTax,2,'.','');
        $this->view->totalPrice      = number_format($shoppingCart->getTotalPrice() + $totalTax + $shipping,2,'.','');
        $this->view->companyAddress  = $shoppingConfig['address'];
        $this->view->keepShoppingUrl = $this->_session->lastUrl;
        $this->view->shippingGeneral = unserialize($shoppingConfig['shipping_general']);
        $this->view->allowShipping   = ($shoppingConfig['shipping_type'] != 'pickup' ? true : false);
        $this->view->shipping        = number_format($shipping,2,'.','');
        $this->view->shippingData    = ($shoppingConfig['shipping_type'] != 'pickup' ? $shippingData->getShippingAddress() : null);
		echo $this->_translator->processScreen($this->view->render($this->getViewScript()));
	}

	private function _countTotalTax($data, $tax) {
		$totalTax = 0;
		foreach($data as $taxableItemData) {
            $catnum = $taxableItemData['taxCategory'];
            $totalTax += ($taxableItemData['pricePerProd'] / 100) * $tax[$catnum];
		}
                return number_format($totalTax,2,'.','');
	}

	public function recountAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		$toRemove   = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('toremove')));
		$toRecount  = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('torecount')));
		$options    = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('options')));
		$remOptions = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('remOptions')));
		$shoppingCart = new RCMS_Object_Shopping_ShoppingCart();
        
		if(!empty($toRemove)) {
			$remOptions = $this->_makeOptions($remOptions);
			foreach ($toRemove as $key => $removeItem) {
				$optKey = str_replace('todelete-', '', $removeItem);
				$removeItem = preg_replace('/todelete-([0-9]+)-[0-9]+/', '$1', $removeItem);
				$shoppingCart->removeItem($removeItem, $remOptions[$optKey]);
			}
		}
		
		if(!empty ($toRecount)) {
			$options = $this->_makeOptions($options);
			foreach ($toRecount as $key => $recountItem) {
				$recountItemData = explode(',', $recountItem);
				$recountItemId = preg_replace('/itmcount-([0-9]+)-[0-9]+/', '$1', $recountItemData[0]);
				$desiredNumber = $recountItemData[1];
				$howManyToAdd = $desiredNumber - $shoppingCart->getItemsCount($recountItemId, $options[$recountItemId . '-' . $key]);
				if($howManyToAdd > 0) {
					$shoppingCart->increaseItemNumber($recountItemId, $howManyToAdd, $options[$recountItemId . '-' . $key]);
				}
				else {
					$shoppingCart->decreaseItemNumber($recountItemId, abs($howManyToAdd), $options[$recountItemId . '-' . $key]);
				}
				if($desiredNumber == 0) {
					$shoppingCart->removeItem($recountItemId, $options[$recountItemId . '-' . $key]);
				}
			}
		}
	}

	private function _makeOptions($options) {
		$rightOpts = array();
		foreach ($options as $optString) {
			$explodedOptString = explode(',', $optString);
			$explodedOptVals = explode('=', $explodedOptString[1]);
			$rightOpts[$explodedOptString[0]][$explodedOptVals[0]] = $explodedOptVals[1];
		}
		return $rightOpts;
	}

	public function sendEmail($to, $toComment, $from, $fromComment, $subject, $body, $useSmtp) {
		$mail = new RCMS_Object_Mailer_Mailer();
		if($useSmtp) {
			$mail->setSmtpConfig($this->_smtpLogin, $this->_smtpPassword, $this->_smtpHost);
			$mail->setTransport(RCMS_Object_Mailer_Mailer::MAIL_TYPE_SMTP);
		}
		$mail->setFrom($fromComment);
		$mail->setFromMail($from);
		$mail->setTo($toComment);
		$mail->setToMail($to);
		$mail->setSubject($subject);
        $mail->setBody($body);
		return $mail->send();
	}

	private function _checkSmtpAllowedInConfig() {
		if(isset($this->_configTableArray['use_smtp']) && $this->_configTableArray['use_smtp'] == 1 &&
			isset($this->_configTableArray['smtp_login']) && $this->_configTableArray['smtp_login'] != '' &&
			isset($this->_configTableArray['smtp_password']) && $this->_configTableArray['smtp_password'] != '') {
			return true;
		}
		return false;
	}

	private function _initSmtp() {
		$this->_domain = ($this->_smtpHost)? ucfirst($this->_smtpHost) : $this->_websiteUrl;
		$configArray = $this->_model->selectAllConfigSettings();
		if($configArray) {
			$this->_configTableArray = $configArray;
			if(isset($configArray['smtp_host']) && $configArray['smtp_host'] != '') {
				$this->_smtpHost = $configArray['smtp_host'];
			}
			if(isset($configArray['smtp_login']) && $configArray['smtp_login'] != '') {
				$this->_smtpLogin = $configArray['smtp_login'];
			}
			if(isset($configArray['smtp_password']) && $configArray['smtp_password'] != '') {
				$this->_smtpPassword = $configArray['smtp_password'];
			}

			$this->_smtpConfigArray = array(
				'auth'      => 'login',
				'username'  => $this->_smtpLogin,
				'password'  => $this->_smtpPassword,
				'host'      => $this->_smtpHost
			);
		}
	}

    public function quotemeAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $generator = new RCMS_Object_Generator_Generator();
        
        if ($this->getRequest()->isPost()) {
            $formData =  $this->getRequest()->getParams();
            $userName = $formData['name'];
            $userEmail = $formData['email'];
            /* get smtp settings */
            $configArray = $this->_model->selectAllConfigSettings();
            $useSmtpInConfig = $this->_checkSmtpAllowedInConfig();
            $shoppingConfig = $this->_model->selectShoppingConfig();

            if ($useSmtpInConfig) {
                $useSmtp = true;
            } else {
                $useSmtp = false;
            }
            
            /* send email to admin from shopping table */
            $subject = 'A new quote request on '.$this->getWebSiteUrl();
            $body = $generator->generateQuoteMailToAdmin($formData);
            $flag = $this->sendEmail($shoppingConfig['email'], $shoppingConfig['company'], $this->_configTableArray['admin_email'], '', $subject, $body, $useSmtp);

            /* send email to client */
            $body = $shoppingConfig['quote_responder_body'];
            $body = str_replace('{$name}', $userName, $body);
            $flag = $this->sendEmail($userEmail, '', $shoppingConfig['email'], $shoppingConfig['company'], $shoppingConfig['quote_responder_subj'], $body, $useSmtp);
            /*saving cart and put a new quote */
            if ($flag) {
                /* load session based cart */
                $shoppingCart = new RCMS_Object_Shopping_ShoppingCart();
                /* create and save cart for current user */
                $userCart = new RCMS_Object_Shopping_ShoppingUserCart();
                $userCart->setName($userName);
                $userCart->setEmail($userEmail);
                $userCart->setCompany($formData['company']);
                $userCart->setAddress1($formData['address1']);
                $userCart->setAddress2($formData['address2']);
                $userCart->setCity($formData['city']);
                $userCart->setCountry($formData['country']);
                $userCart->setState($formData['state']);
                $userCart->setZip($formData['zip']);
                $userCart->setPhone($formData['phone']);
                $userCart->setComments(strip_tags($formData['comments']));
                $userCart->setCartData($shoppingCart->getProductsList());
                $newCartId = $userCart->save();
                /* creating new quote */
                $quote = new RCMS_Object_Quote_Quote();
                $quote->setShoppingCartId($newCartId);
                $quote->setName($userName);
                $quote->setShipping($this->_session->shipping['total']);
                $quote->setStatus(RCMS_Object_Quote_Quote::Q_STATUS_NEW);
                $quote->save();
                /* saving shipping address */
                if ($shoppingConfig['shipping_type'] != 'pickup'){
                    $shippingData = new RCMS_Object_Shipping_Shipping();
                    $shippingData->setCartId($newCartId);
                    $shippingData->saveShipping();
                }
                echo json_encode(array('done' => true)); return;
            }
            echo json_encode(array('done' => false)); return;
		}
    }

    /**
     * This handler for paypal account. (AJAX)
     */
    public function handlerpaypalaccountAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

        $shoppingConfig = $this->_model->selectShoppingConfig();

        if ($this->getRequest()->isPost()) {
            $data =  $this->getRequest()->getParams();

            if ($data['payment_type'] == 'instant') {
                unset ($data['controller']);
                unset ($data['action']);
                unset ($data['module']);
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, 'https://www.paypal.com/cgi-bin/webscr');
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_VERBOSE, 1);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array_merge(array('cmd'=>'_notify-validate'), $data)));
                $response = curl_exec($ch);
                curl_close($ch);

                if ($response == 'VERIFIED') {
                    $dataPayment = array(
                        'transaction_id'    =>  $data['txn_id'],
                        'amount'            =>  $data['mc_gross'],
                        'payer_id'          =>  $data['payer_id'],
                        'description'       =>  $data['item_name'],
                        'billing_name'      =>  $data['address_name'],
                        'billing_email'     =>  $data['payer_email'],
                        'billing_address'   =>  $data['address_street'],
                        'billing_address1'  =>  $data['address_street'],
                        'billing_country'   =>  $data['address_country'],
                        'billing_city'      =>  $data['address_city'],
                        'billing_state'     =>  $data['address_state'],
                        'billing_zip'       =>  $data['address_zip'],
                        'date'              =>  date('Y-n-d G-i-s'),
                        'sc_id'             =>  '0'
                    );
                    $this->_model->insertShoppingPayPalPayment($dataPayment);

                    /* sending email to store admin */
                    $useSmtp = $this->_checkSmtpAllowedInConfig();
                    $subject = 'New PayPal payment arrived to ' . $this->getWebSiteUrl();
                    $body  = 'New PayPal payment arrived:<br />';
                    $body .= 'Transaction ID: ' .$dataPayment['transaction_id']. '<br>';
                    $body .= 'Description: ' .$dataPayment['description']. '<br>';
                    $body .= 'Amount: ' . $dataPayment['amount'] . '<br>';
                    $body .= 'Date: ' . $dataPayment['date'];
                    $this->sendEmail($shoppingConfig['email'], '', $this->_configTableArray['admin_email'], $this->getWebSiteUrl(), $subject, $body, $useSmtp);
                }
            }
        }
    }

    /**
     * This handler for credit cart using the service of paypal. (AJAX)
     * @return <string> (json)
     */
    public function handlerpaypalcreditcardAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
        $shoppingConfig = $this->_model->selectShoppingConfig();
        
        if ($this->getRequest()->isPost()) {
            $data =  $this->getRequest()->getParams();
            
            $dataForPayment = array(
                'PAYMENTACTION'     =>  'Sale',
                'IPADDRESS'         =>  $_SERVER['REMOTE_ADDR'],
                'CREDITCARDTYPE'    =>  $data['type'],
                'ACCT'              =>  trim($data['cardnumber']),
                'EXPDATE'           =>  str_pad($data['expiration_date_month'], 2, '0', STR_PAD_LEFT).$data['expiration_date_year'],
                'CVV2'              =>  trim($data['verification_number']),
                'EMAIL'             =>  trim($data['email']),
                'FIRSTNAME'         =>  trim($data['firstname']),
                'LASTNAME'          =>  trim($data['lastname']),
                'STREET'            =>  trim($data['billing_address1']),
                'STREET2'           =>  trim($data['billing_address2']),
                'CITY'              =>  trim($data['city']),
                'STATE'             =>  $data['state'],
                'COUNTRYCODE'       =>  $data['country'],
                'ZIP'               =>  trim($data['zip']),
                'PHONENUM'          =>  trim($data['phone']),
                'AMT'               =>  $data['amt'] + ($data['tax'] !== '' ? $data['tax'] : '0') + ($data['shipping'] !== '' ? $data['shipping'] : '0'),
                        //($data['tax'] !== '0' ? $data['amt'] + $data['tax'] : $data['amt']),
                'CURRENCYCODE'      =>  $data['currency_code'],
                'DESC'              =>  $data['desc']
            );
            
            /*if ($data['tax'] !== '' && $data['tax'] !== '0') {
                $dataForPayment['TAXAMT'] = $data['tax'];
            }*/
            
            $objPayPal = new RCMS_Object_PayPal_PayPal();
            $payment = $objPayPal->createDoDirectPayment($dataForPayment);

            if (preg_match('/success/i', $payment['ACK']) && isset($payment['TRANSACTIONID'])) {
                $infoPayment = $objPayPal->getTransactionDetails($payment['TRANSACTIONID']);
                
                if (preg_match('/success/i', $infoPayment['ACK'])) {
                    /* load session based cart */
                    $shoppingCart = new RCMS_Object_Shopping_ShoppingCart();

                    /* create and save cart for current user */
                    $userCart = new RCMS_Object_Shopping_ShoppingUserCart();
                    $userCart->setName(trim($data['firstname']).' '.trim($data['lastname']));
                    $userCart->setEmail(trim($data['email']));
                    $userCart->setCompany();
                    $userCart->setAddress1(trim($data['billing_address1']));
                    $userCart->setAddress2(trim($data['billing_address2']));
                    $userCart->setCity(trim($data['city']));
                    $userCart->setCountry($data['country']);
                    $userCart->setState($data['state']);
                    $userCart->setZip(trim($data['zip']));
                    $userCart->setPhone(trim($data['phone']));
                    $userCart->setComments('Paypal Transaction ID: '.$infoPayment['TRANSACTIONID']);
                    $userCart->setCartData($shoppingCart->getProductsList());
                    $newCartId = $userCart->save();

                    /* loading shipping data from session */
                    /* and saving shipping data */
                    if ($shoppingConfig['shipping_type'] != 'pickup'){
                        $shippingData = new RCMS_Object_Shipping_Shipping();
                        $shippingData->setCartId($newCartId);
                        $shippingData->saveShipping();
                    }

                    /* saving payment details*/
                    $dataPayment = array(
                        'transaction_id'    =>  $infoPayment['TRANSACTIONID'],
                        'amount'            =>  $infoPayment['AMT'],
                        'payer_id'          =>  $infoPayment['PAYERID'],
                        'description'       =>  $data['desc'],
                        'billing_name'      =>  trim($data['firstname']).' '.trim($data['lastname']),
                        'billing_email'     =>  (isset($infoPayment['EMAIL'])?$infoPayment['EMAIL']:''),
                        'billing_address'   =>  trim($data['billing_address1']),
                        'billing_address1'  =>  trim($data['billing_address2']),
                        'billing_country'   =>  $data['country'],
                        'billing_city'      =>  trim($data['city']),
                        'billing_state'     =>  $data['state'],
                        'billing_zip'       =>  trim($data['zip']),
                        'date'              =>  date('Y-n-d G-i-s'),
                        'sc_id'             =>  $newCartId
                    );
                    $this->_model->insertShoppingPayPalPayment($dataPayment);

                    /* send e-mail to store administrator */
                    $useSmtp = $this->_checkSmtpAllowedInConfig();
                    $subject = 'New PayPal payment arrived to ' . $this->getWebSiteUrl();
                    $body  = 'New PayPal payment arrived:<br />';
                    $body .= 'Transaction ID: ' .$dataPayment['transaction_id']. '<br>';
                    $body .= 'Description: ' .$dataPayment['description']. '<br>';
                    $body .= 'Amount: ' . $dataPayment['amount'] . '<br>';
                    $body .= 'Date: ' . $dataPayment['date'];
                    $this->sendEmail($shoppingConfig['email'], '', $this->_configTableArray['admin_email'], $this->getWebSiteUrl(), $subject, $body, $useSmtp);

                    echo json_encode(array('done' => true)); return;
                }
                echo json_encode(array('done' => false)); return;
            }
            echo json_encode(array('done' => false)); return;
        }
    }

    /**
     *  internal function uses for validating shipping config data 
     */
    private function _validateShippingData($item, $key) {
        if (!preg_match('/^(\d+(\.\d+)?)?$/', $item)) {
            array_push($this->_error,$key);
        }
    }

    /**
     * Action to count shipping according to shipping data in config
     * @return void
     * @deprecated
     */
    public function countshippingAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        if ($this->getRequest()->isPost()){
            $shippingTotal = 0;
            $shoppingConfig  = $this->_model->selectShoppingConfig();
            $shippingGeneral = unserialize($shoppingConfig['shipping_general']);
            $shoppingCart    = new RCMS_Object_Shopping_ShoppingCart();
            
            $userData = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('shipping_data')));
            if (trim($userData->country) == '') {
                $this->_session->shipping = array ('type' => 'no data', 'total'=> 0);
                echo $this->_session->shipping;
                return;
            }

            switch ($shoppingConfig['shipping_type']) {
                case 'pickup':
                    $this->_session->shipping = array ('type' => 'pickup', 'total'=> 0);
                    echo $this->_session->shipping;
                    return;
                    break;

                case 'amount':
                    $shippingAmount = unserialize($shoppingConfig['shipping_amount']);
                    $shippingType = ($userData->country == $shoppingConfig['country'] ? 'national' : 'international');
                    $amount = $shoppingCart->getTotalPrice();
                    
                    switch ($amount){

                        case ($amount < $shippingAmount[1]['limit']):
                            $shippingTotal = $shippingAmount[1][$shippingType];
                            break;

                        case ($amount < $shippingAmount[2]['limit']):
                            $shippingTotal = $shippingAmount[2][$shippingType];
                            break;

                        case ($amount > $shippingAmount[3]['limit']):
                            $shippingTotal = $shippingAmount[3][$shippingType];
                            if ($amount > $shippingGeneral['free-shipping-over']){
                                if ($shippingGeneral['free-shipping-options'] == $shippingType) {
                                    $shippingTotal = '0';
                                } else if ($shippingGeneral['free-shipping-options'] == 'both') {
                                    $shippingTotal = '0';
                                }
                            }
                            break;

                        default:
                            break;
                    }
                    break;

                case 'weight':
                    $shippingWeight = unserialize($shoppingConfig['shipping_weight']);
                    $shippingType = ($userData->country == $shoppingConfig['country'] ? 'national' : 'international');
                    $weight = $shoppingCart->getTotalWeight();
                    switch ($weight){
                        case ($weight < $shippingWeight[1]['limit']):
                            $shippingTotal = $shippingWeight[1][$shippingType];
                            break;
                        case ($weight < $shippingWeight[2]['limit']):
                            $shippingTotal = $shippingWeight[2][$shippingType];
                            break;
                        case ($weight > $shippingWeight[3]['limit']):
                            $shippingTotal = $shippingWeight[3][$shippingType];
                            break;
                    }
                    break;
                default:
                    return false;
                    break;
            }

        }
        $this->_session->shipping = array ('type' => $shippingType, 'total'=> $shippingTotal);
        $this->_session->shippingData = $userData;

        echo json_encode($this->_session->shipping);
        return;

    }

    /**
     * Method loads taxes configuration screen
     */
    public function taxesAction() {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        $this->_error = array();
        $rules = array ();
        if ($this->getRequest()->isPost()){
            $taxrules = $this->getRequest()->getParam('taxrule');
            
            foreach ($taxrules as $num => $rule) {
                if (strlen(trim(implode('',$rule['tax']))) == '0') {
                    unset($taxrules[$num]);
                    continue;
                }
                foreach ($rule['tax'] as $key => &$value) {
                    if (!is_numeric($value)) {
                        array_push ($this->_error, $value);
                    } 
                }
            }

            if (count($this->_error)){
                $this->view->update = false;
                $this->view->error = true;
            } else {
                $data   = serialize($taxrules);
                $labels = serialize(array_merge(array('0'=>'non taxable'),$this->getRequest()->getParam('label')));

                $this->_model->updateShoppingConfig('tax-rules', $data);
                $this->_model->updateShoppingConfig('tax-labels', $labels);
                $this->view->update = true;
                $this->view->error = false;
            }
        }
        
        $this->view->taxrules = unserialize($this->_model->selectTaxRules());
        $this->view->labels   = unserialize($this->_model->selectTaxLabels());
        
        echo $this->_translator->processScreen($this->view->render($this->getViewScript()));
    }

    /**
     * Calculating total tax for the cart (AJAX)
     * @param <type> $param
     */
    public function counttaxAction() {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        $totalTax = 0;
        $itemsTaxes = array();
        
        if ($this->getRequest()->isPost()){

            $userCountry = trim($this->getRequest()->getParam('userCountry'));
            $userState   = trim($this->getRequest()->getParam('userState'));

            $shoppingCart = new RCMS_Object_Shopping_ShoppingCart();

            $taxableProducts = $shoppingCart->getTaxableItemsData();
            $taxRules =   unserialize($this->_model->selectTaxRules());

            foreach ($taxRules as $rule) {
                if (($rule['zone'] == $userCountry && $userState != '' && strpos($rule['subzone'],$userState)!==false)
                        || (($userState == '' || empty($userState)) && strpos($rule['subzone'],$userCountry)!==false) ){
                    $totalTax = $this->_countTotalTax($taxableProducts, $rule['tax']);

                    foreach ($taxableProducts as $product) {
                        $itemsTaxes[$product['id']] = number_format(($product['pricePerProd']/100) * $rule['tax'][$product['taxCategory']],2,'.','');
                    }
                }
            }
        }
        $this->_session->totalTax = $totalTax;
        $this->_session->taxPerItems  = $itemsTaxes;
        echo json_encode(array('totaltax' => $totalTax, 'taxPerItem' => $itemsTaxes));
    }

}
